// MongoDB初始化脚本

// 切换到admin数据库
db = db.getSiblingDB('admin');

// 创建应用用户
db.createUser({
  user: 'iot_user',
  pwd: 'iot_pass123',
  roles: [
    {
      role: 'readWrite',
      db: 'iot_platform'
    }
  ]
});

// 切换到应用数据库
db = db.getSiblingDB('iot_platform');

// 创建集合
db.createCollection('devices');
db.createCollection('heartbeat_logs');
db.createCollection('device_logs');

// 创建索引
db.devices.createIndex({ deviceId: 1 }, { unique: true });
db.devices.createIndex({ status: 1 });
db.devices.createIndex({ lastHeartbeatTime: -1 });

db.heartbeat_logs.createIndex({ deviceId: 1 });
db.heartbeat_logs.createIndex({ timestamp: -1 });
db.heartbeat_logs.createIndex({ deviceId: 1, timestamp: -1 });

db.device_logs.createIndex({ deviceId: 1 });
db.device_logs.createIndex({ timestamp: -1 });
db.device_logs.createIndex({ eventType: 1 });

// 插入示例设备数据
db.devices.insertMany([
  {
    deviceId: 'device_001',
    deviceName: '测试设备001',
    status: 'offline',
    lastOnlineTime: null,
    lastHeartbeatTime: null,
    ipAddress: '',
    createdAt: new Date(),
    updatedAt: new Date()
  },
  {
    deviceId: 'device_002',
    deviceName: '测试设备002',
    status: 'offline',
    lastOnlineTime: null,
    lastHeartbeatTime: null,
    ipAddress: '',
    createdAt: new Date(),
    updatedAt: new Date()
  }
]);

print('MongoDB初始化完成！');

